{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 假设有一个PH值计算的函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "pH值为：4.0\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "\n",
    "def calculate_ph(h_plus=None, oh_minus=None, temperature=25):\n",
    "    \"\"\"\n",
    "    计算pH值的函数。\n",
    "    \n",
    "    参数:\n",
    "    h_plus (float): 氢离子浓度（单位：mol/L）\n",
    "    oh_minus (float): 氢氧根离子浓度（单位：mol/L）\n",
    "    temperature (float): 温度（单位：摄氏度），默认值为25℃\n",
    "    \n",
    "    返回:\n",
    "    float: pH值\n",
    "    \"\"\"\n",
    "    # 水的离子积常数Kw随温度变化\n",
    "    # 这里使用一个简化的Kw计算公式，实际应用中可能需要更精确的数据\n",
    "    kw = 10**(-14 + 0.016*(temperature - 25))\n",
    "    \n",
    "    if h_plus is not None:\n",
    "        # 如果已知氢离子浓度，直接计算pH\n",
    "        ph = -math.log10(h_plus)\n",
    "    elif oh_minus is not None:\n",
    "        # 如果已知氢氧根离子浓度，先计算pOH，再转换为pH\n",
    "        poh = -math.log10(oh_minus)\n",
    "        ph = 14 - poh\n",
    "    else:\n",
    "        raise ValueError(\"必须提供氢离子浓度或氢氧根离子浓度\")\n",
    "    \n",
    "    return ph\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # 示例用法\n",
    "    h_plus = 0.0001    # 氢离子浓度（单位：mol/L）\n",
    "    oh_minus = 0.01 # 氢氧根离子浓度（单位：mol/L）\n",
    "    temperature = 30 # 温度（单位：摄氏度）\n",
    "    \n",
    "    ph = calculate_ph(h_plus=h_plus, oh_minus=oh_minus, temperature=temperature)\n",
    "    print(f\"pH值为：{ph}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "返回的消息:\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from dashscope import Generation\n",
    "from datetime import datetime\n",
    "import random\n",
    "\n",
    "# 定义工具列表，模型在选择使用哪个工具时会参考工具的name和description\n",
    "tools = [\n",
    "   # 工具1 获取当前时刻的时间\n",
    " {\n",
    "       \"type\": \"function\",\n",
    "       \"function\": {\n",
    "           \"name\": \"get_current_time\",\n",
    "           \"description\": \"当你想知道现在的时间时非常有用。\",\n",
    "           \"parameters\": {}  # 因为获取当前时间无需输入参数，因此parameters为空字典\n",
    "     }\n",
    " },  \n",
    "   # 工具2 获取指定城市的天气\n",
    " {\n",
    "       \"type\": \"function\",\n",
    "       \"function\": {\n",
    "           \"name\": \"get_current_weather\",\n",
    "           \"description\": \"当你想查询指定城市的天气时非常有用。\",\n",
    "           \"parameters\": {  # 查询天气时需要提供位置，因此参数设置为location\n",
    "                       \"type\": \"object\",\n",
    "               \"properties\": {\n",
    "                   \"location\": {\n",
    "                       \"type\": \"string\",\n",
    "                       \"description\": \"城市或县区，比如北京市、杭州市、余杭区等。\"\n",
    "                 }\n",
    "             }\n",
    "         },\n",
    "           \"required\": [\n",
    "               \"location\"\n",
    "         ]\n",
    "     }\n",
    " }\n",
    "]\n",
    "\n",
    "# 模拟天气查询工具。返回结果示例：“北京今天是晴天。”\n",
    "def get_current_weather(location):\n",
    "   return f\"{location}今天是晴天。 \"\n",
    "\n",
    "# 查询当前时间的工具。返回结果示例：“当前时间：2024-04-15 17:15:18。“\n",
    "def get_current_time():\n",
    "   # 获取当前日期和时间\n",
    "   current_datetime = datetime.now()\n",
    "   # 格式化当前日期和时间\n",
    "   formatted_time = current_datetime.strftime('%Y-%m-%d %H:%M:%S')\n",
    "   # 返回格式化后的当前时间\n",
    "   return f\"当前时间：{formatted_time}。\"\n",
    "\n",
    "# 封装模型响应函数\n",
    "import ollama\n",
    "client = ollama.Client(host='http://192.168.20.43:11434')\n",
    "\n",
    "def get_response(messages):\n",
    "    system_prompt = \"\"\n",
    "    prompt = messages\n",
    "    response = client.chat(\n",
    "        model='qwen2.5:14b', \n",
    "        tools=tools,\n",
    "        options={\n",
    "            \"num_ctx\": 32768,  # 设置 num_ctx 参数\n",
    "            \"temperature\": 0.7,  # 设置 temperature 参数\n",
    "            \"top_p\": 0.9  # 设置 top_p 参数\n",
    "            # 可以添加的其他参数:\n",
    "            # \"max_tokens\": 150,  # 设置最大生成的token数量\n",
    "            # \"stop\": [\"\\n\", \"结束\"],  # 设置停止生成的token\n",
    "            # \"stream\": False,  # 是否启用流式响应\n",
    "            # \"presence_penalty\": 0.0,  # 设置存在惩罚\n",
    "            # \"frequency_penalty\": 0.0,  # 设置频率惩罚\n",
    "            # \"logprobs\": None,  # 设置返回log概率\n",
    "            # \"echo\": False,  # 是否回显输入\n",
    "            # \"n\": 1,  # 设置生成的回复数量\n",
    "        },\n",
    "        messages=[{'role': 'system', 'content': system_prompt},\n",
    "                  {'role': 'user', 'content': prompt}],\n",
    "    )\n",
    "    return response['message']['content']\n",
    "\n",
    "def call_with_messages():\n",
    "   messages = \"北京天气如何\"\n",
    "   \n",
    "   # 模型的第一轮调用\n",
    "   assistant_output = get_response(messages)\n",
    "   print(\"返回的消息:\")\n",
    "   print(assistant_output)\n",
    "#    messages.append(assistant_output)\n",
    "#    if 'tool_calls' not in assistant_output:  # 如果模型判断无需调用工具，则将assistant的回复直接打印出来，无需进行模型的第二轮调用\n",
    "#        print(assistant_output.content)\n",
    "#        return\n",
    "#    # 如果模型选择的工具是get_current_weather\n",
    "#    elif assistant_output.tool_calls[0]['function']['name'] == 'get_current_weather':\n",
    "#        tool_info = {\"name\": \"get_current_weather\", \"role\":\"tool\"}\n",
    "#        location = assistant_output.tool_calls[0]['function']['arguments']\n",
    "#        print(f\"调用天气的参数:{location}\")\n",
    "#        tool_info['content'] = get_current_weather(location)\n",
    "#    # 如果模型选择的工具是get_current_time\n",
    "#    elif assistant_output.tool_calls[0]['function']['name'] == 'get_current_time':\n",
    "#        tool_info = {\"name\": \"get_current_time\", \"role\":\"tool\"}\n",
    "#        tool_info['content'] = get_current_time()\n",
    "#    messages.append(tool_info)\n",
    "\n",
    "#    print(messages)\n",
    "\n",
    "#    # 模型的第二轮调用，对工具的输出进行总结\n",
    "#    response = get_response(messages)\n",
    "#    print(f\"模型回复：{response.output.choices[0].message['content']}\")\n",
    "\n",
    "   \n",
    "if __name__ == '__main__':\n",
    "   call_with_messages()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
